﻿using System;
using System.Data.SqlClient;

namespace GianosNET.Services.CronSVC.classes
{
    public class SqlCmdTask:Task
    {
        public SqlCmdTask(string id, TaskTypeEnum type, bool enabled, string crontabString, bool executeImmediately)
            : base(id, type, enabled, crontabString, executeImmediately)
        {
            
        }

        protected override void PopulateAdditionalParameters(System.Xml.XPath.XPathNavigator task)
        {
            Parameters = new AdditionalAttributes()
                             {
                                 {"connectionString", null},
                                 {"commandText", null},
                                 {"timeOut", null}
                             };

            base.PopulateAdditionalParameters(task);
        }

        public override string Execute()
        {
            string res = "";

            try
            {

                int tOut = -1;
                int.TryParse(Parameters["timeOut"], out tOut);

                using (SqlConnection conn = new SqlConnection(Parameters["connectionString"]))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(Parameters["commandText"], conn))
                    {
                        cmd.CommandType = System.Data.CommandType.Text;
                        cmd.CommandTimeout = tOut > 0 ? tOut : 30;
                        res = "Righe coinvolte: "+ cmd.ExecuteNonQuery().ToString();
                    }
                    conn.Close();
                }

                res = string.Format("Comando eseguito con successo ({0})", res);
            }
            catch(Exception ex)
            {
                res = string.Format("Si è verificato un errore: {0}", ex.Message);
            }
            finally
            {
                base.Execute();
            }
            return res;
        }
    }
}
